/**@author: Administrator
 * @date: 2013-3-7
 * @Description:
 */
package org.benxiong.iplay.ui;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.params.HttpParams;
import org.benxiong.iplay.R;
import org.benxiong.iplay.http.request.RequestFactory;
import org.benxiong.iplay.model.UserPhoto;
import org.benxiong.iplay.ui.adapter.UserPhotoAdapter;
import org.benxiong.iplay.util.ImageUtil;
import org.benxiong.iplay.util.LogX;
import org.benxiong.iplay.util.ObjectConverter;
import org.benxiong.iplay.util.ToastUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * @author Administrator
 * 
 */
public class PhotoManagerActivity extends BaseActivity implements OnItemClickListener {
	public static final String	PHOTO_TYPE_ALBUM		= "0";
	public static final String	PHOTO_TYPE_COVER		= "1";
	public static final String	PHOTO_TYPE_AVATOR		= "2";

	public static final int		REQ_CODE_PUBLIC_ALBUM	= 0;
	public static final int		REQ_CODE_PRIVATE_ALBUM	= 1;
	public static final int		REQ_CODE_PROFILE_COVER	= 2;
	
	public static final String[] picOptions = new String[]{"", "", ""};

	private GridView			publicGrV;
	private GridView			privateGrV;
	private UserPhotoAdapter	publicAdapter;
	private UserPhotoAdapter	privateAdapter;

	private List<UserPhoto>		userPublicPhotoList		= new ArrayList<UserPhoto>();
	private List<UserPhoto>		userPrivatePhotoList	= new ArrayList<UserPhoto>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.benxiong.iplay.ui.BaseActivity#initView()
	 */
	@Override
	protected void initView() {
		setContentView(R.layout.photo_manager);

		publicGrV = (GridView) findViewById(R.id.public_photos);
		privateGrV = (GridView) findViewById(R.id.private_photos);

		publicAdapter = new UserPhotoAdapter(this);
		privateAdapter = new UserPhotoAdapter(this);
		publicGrV.setAdapter(publicAdapter);
		privateGrV.setAdapter(privateAdapter);
		
		publicGrV.setOnItemClickListener(this);
		privateGrV.setOnItemClickListener(this);
		
		reqMyPhotos();
	}

	private void reqMyPhotos() {
		showLoading();
		RequestFactory.getInstance().post(RequestFactory.URL_MY_PHOTOS, null, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				LogX.print("content===" + content);
				try {
					if (shouldProcess(content)) {
						JSONObject json = new JSONObject(content);
						JSONArray array = json.getJSONArray("data");
						userPublicPhotoList.clear();
						userPrivatePhotoList.clear();
						for (int i = 0; i < array.length(); i++) {
							UserPhoto up = ObjectConverter.jsonToUserPhoto(array.getJSONObject(i));
							if (up.getAccess() == 0) {
								userPublicPhotoList.add(up);
							} else {
								userPrivatePhotoList.add(up);
							}
						}
						publicAdapter.addData(userPublicPhotoList);
						privateAdapter.addData(userPrivatePhotoList);
						publicGrV.setAdapter(publicAdapter);
						privateGrV.setAdapter(privateAdapter);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
			}

		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.benxiong.iplay.ui.BaseActivity#onMessage(android.os.Message)
	 */
	@Override
	public void onMessage(Message msg) {

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.upload_cover:
			Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
			getImage.addCategory(Intent.CATEGORY_OPENABLE);
			getImage.setType("image/jpeg");
			startActivityForResult(getImage, REQ_CODE_PROFILE_COVER);
			break;
		case R.id.upload_public:
			getImage = new Intent(Intent.ACTION_GET_CONTENT);
			getImage.addCategory(Intent.CATEGORY_OPENABLE);
			getImage.setType("image/jpeg");
			startActivityForResult(getImage, REQ_CODE_PUBLIC_ALBUM);
			break;
		case R.id.upload_private:
			getImage = new Intent(Intent.ACTION_GET_CONTENT);
			getImage.addCategory(Intent.CATEGORY_OPENABLE);
			getImage.setType("image/jpeg");
			startActivityForResult(getImage, REQ_CODE_PRIVATE_ALBUM);
			break;
		case R.id.upload_reload:
			this.reqMyPhotos();
			break;
		default:
			super.onOptionsItemSelected(item);
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.benxiong.iplay.ui.BaseActivity#handleClick(int)
	 */
	@Override
	public void handleClick(int buttonId) {

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.photos_option_menu, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode >= 0) {
			// handle picture chosen action
			try {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();

				int maxWidth = 1024;
				final ByteArrayInputStream bs = ImageUtil.getResizedInputStreamFromFile(picturePath, maxWidth);

				// upload to server
				RequestParams rp = new RequestParams();
				rp.put("file", bs);
				switch (requestCode) {
				case REQ_CODE_PROFILE_COVER:
					rp.put("type", PHOTO_TYPE_COVER);
					break;
				case REQ_CODE_PRIVATE_ALBUM:
					rp.put("type", PHOTO_TYPE_ALBUM);
					rp.put("access", "1");
					break;
				case REQ_CODE_PUBLIC_ALBUM:
					rp.put("type", PHOTO_TYPE_ALBUM);
					rp.put("access", "0");
					break;
				}

				LogX.print("========uploading Pic-=======");
				showLoading(R.string.uploading);
				RequestFactory.getInstance().post(RequestFactory.URL_UPLOAD_PHOTO, rp, new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable arg0) {
						super.onFailure(arg0);
						try {
							bs.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
						ToastUtil.toast(R.string.upload_fail);
					}

					@Override
					public void onSuccess(String arg0) {
						super.onSuccess(arg0);
						try {
							if (shouldProcess(arg0)) {
								ToastUtil.toast(R.string.upload_success);
							}
							bs.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

				});
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		UserPhoto photo = (UserPhoto) adapter.getItemAtPosition(position);
		final String photoId = photo.getId();
		final String to = photo.getAccess() == 0 ? "1" : "0";
		
		new AlertDialog.Builder(this).setItems(R.array.picOptions, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String url = "";
				RequestParams rParam = new RequestParams();
				showLoading(R.string.operating);
				switch(which) {
				case 0:
					//move
					rParam.put("ids[]", photoId);
					rParam.put("to", to);
					url = RequestFactory.URL_MOVE_PHOTOS;
					LogX.print("moving id: " + photoId + " to: " + to);
					break;
				case 1:
					//set as profile
					rParam.put("photoId", photoId);
					url = RequestFactory.URL_SET_AS_PROFILE;
					break;
				case 2:
					//delete
					rParam.put("ids[]", photoId);
					url = RequestFactory.URL_DELETE_PHOTOS;
					break;
					
				}
				
				RequestFactory.getInstance().post(url, rParam, new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						// TODO Auto-generated method stub
						super.onFailure(error);
						ToastUtil.toast(R.string.operation_fail);
						LogX.print("error = "+error.getMessage());
					}

					
					@Override
					public void onFailure(Throwable error, String content) {
						// TODO Auto-generated method stub
						super.onFailure(error, content);
						LogX.print("error = "+content);
					}


					@Override
					public void onSuccess(String content) {
						// TODO Auto-generated method stub
						super.onSuccess(content);
						try {
							if (shouldProcess(content)) {
								ToastUtil.toast(R.string.operation_success);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				});
				
			}
		}).create().show();
		
	}

	

}
